package wec_wallet.ebo.com.activity.capital;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import bassproject.ebo.com.ebobass.activity.MyBaseActivity;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import wec_wallet.ebo.com.utils.URLs;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.JsonT;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.bean.Address;
import wec_wallet.ebo.com.bean.Coin;
import wec_wallet.ebo.com.common.Constants;
import wec_wallet.ebo.com.util.ChangeUtil;
import wec_wallet.ebo.com.utils.Functions;
import wec_wallet.ebo.com.widget.AddressSpinnerPop;
import wec_wallet.ebo.com.widget.CoinOutSpinnerPop;

/**
 * 转出
 */
public class TurnOutActivity extends MyBaseActivity {
    private final int REFRESHADDRESS = 10002;

    @BindView(R.id.turn_out_balance)
    TextView turnOutBalance;
    @BindView(R.id.turn_out_address_spinner)
    TextView turnOutAddressSpinner;
    @BindView(R.id.turn_out_address)
    TextView turnOutAddress;
    @BindView(R.id.turn_out_common_address)
    TextView turnOutCommonAddress;
    @BindView(R.id.turn_out_money)
    EditText turnOutMoney;
    @BindView(R.id.turn_out_cny)
    TextView turnOutCny;
    @BindView(R.id.turn_out_tax_rate)
    TextView turnOutTaxRate;
    @BindView(R.id.turn_out_submit)
    Button turnOutSubmit;
    @BindView(R.id.turn_out_prompt)
    TextView turnOutPrompt;
    @BindView(R.id.txtvwSpinner)
    TextView txtvwSpinner;
    ArrayList<Coin> list = new ArrayList<>();
    ArrayList<Address> addressArrayList = new ArrayList<>();
    String coinname;
    AddressSpinnerPop addressSpinnerPop;
    /**
     * 地址选择监听
     */
    AdapterView.OnItemClickListener listenerAddress = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (addressArrayList.size() == 1 || addressArrayList.size() - 1 == i) {
                startActivityForResult(new Intent(TurnOutActivity.this, AccountAddressActivity.class)
                        .putExtra(Constants.WALLETID, coinname), REFRESHADDRESS);
            } else {
                setFraud(addressArrayList.get(i));
            }
            addressSpinnerPop.dismiss();
        }

    };

    @BindView(R.id.turn_out_balance_name)
    TextView turnOutBalanceName;
    private Handler handler = new Handler();
    private String editString;
    /**
     * h获取品种详情
     *
     * @param name
     */
    private Coin coin;
    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun = new Runnable() {
        @Override
        public void run() {
            if (!TextUtils.isEmpty(editString) && !editString.equals(".")) {
                double v = Double.parseDouble(editString);
                if (v != 0) {
                    if (coin == null || coin.getNum() == null || v > coin.getNum()) {
                        IToast.show(getResources().getString(R.string.balance_not_enough));
                        turnOutCny.setText(getResources().getString(R.string.balance_not_enough));
                        turnOutCny.setTextColor(Color.RED);
                        turnOutTaxRate.setText("");
                        return;
                    } else if (coin.getZc_min_fee() == null || coin.getZc_fee_proportion() == null || coin.getCny_price_num() == null) {
                        IToast.show(getResources().getString(R.string.data_error));
                        return;
                    } else {
                        getTransferRate(v);
                        turnOutCny.setTextColor(getResources().getColor(R.color.black_3a));
                    }
                }
            }
        }
    };
    CoinOutSpinnerPop coinSpinnerPop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_turn_out);
        ButterKnife.bind(this);
        coinname = getIntent().getStringExtra(Constants.WALLETID);
        boolean flag = getIntent().getBooleanExtra("flag", false);
        boolean from = getIntent().getBooleanExtra("from", false);
        if(from){
            txtvwSpinner.setVisibility(View.GONE);
        }



        if (flag) {
            startActivityForResult(new Intent(TurnOutActivity.this, AccountAddressActivity.class)
                   .putExtra("flag", true), REFRESHADDRESS);
        }
        coinSpinnerPop = new CoinOutSpinnerPop(this, list);
        coinSpinnerPop.setOnItemClick(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (list.size() < 1)
                    return;
                coinname = list.get(i).getWallet_id();
                refreshInfo(list.get(i).getWallet_name());
                coinSpinnerPop.dismiss();
                turnOutBalanceName.setText(getResources().getString(R.string.balance_btc));
            }
        });
        coinSpinnerPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                drawable = getResources().getDrawable(R.drawable.arrow);  //(API 21以上才能使用此方法)
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                txtvwSpinner.setCompoundDrawables(null, null, drawable, null);
            }
        });
        addressSpinnerPop = new AddressSpinnerPop(this, addressArrayList);
        addressSpinnerPop.setOnItemClick(listenerAddress);
        addressSpinnerPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                drawable = getResources().getDrawable(R.drawable.arrow_down);  //(API 21以上才能使用此方法)
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                turnOutAddressSpinner.setCompoundDrawables(null, null, drawable, null);
            }
        });
        findViewById(R.id.actionbar_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getSubjectList();
        turnOutMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (delayRun != null) {
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    handler.removeCallbacks(delayRun);
                }
                editString = editable.toString().trim();
                //延迟1000ms，如果不再输入字符，则执行该线程的run方法
                handler.postDelayed(delayRun, 1000);
            }
        });
    }

    @Override
    public void initViews() {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerTimer.removeCallbacksAndMessages(null);
        try {
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            if (task != null) {
                task.cancel();
                task = null;
            }
        } catch (Exception e) {

        }
    }

    @OnClick({R.id.turn_out_common_address, R.id.turn_out_submit, R.id.turn_out_address_spinner, R.id.txtvwSpinner})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.turn_out_common_address:
                startActivityForResult(new Intent(TurnOutActivity.this, ManagerAccountActivity.class)
                        .putExtra(Constants.WALLETID, coinname), REFRESHADDRESS);
                break;
            case R.id.turn_out_submit:
                submitChangeOut();
                break;
            case R.id.turn_out_address_spinner:
                addressSpinnerPop.showPopupWindow(turnOutAddressSpinner);
                setArrowImage();
                break;
            case R.id.txtvwSpinner:
                coinSpinnerPop.showPopupWindow(txtvwSpinner);
                setArrowImageCoin();
                break;
        }
    }

    /**
     * 获取品种列表
     */
    private void getSubjectList() {
        if (I_Share.isLogin()) {
            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            Functions.post(this,URLs.COINLIST, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {

                }

                @Override
                public void responseSuccess(String result) {
                    if (Ipost.isTimeOut(result)) {
                        return;
                    }
                    try {
                        if (!TextUtils.isEmpty(result)) {
                            JsonT<ArrayList<Coin>> json = JSON.parseObject(result, new TypeReference<JsonT<ArrayList<Coin>>>() {
                            });
                            if (json.getIs_auth() != null && json.getIs_auth() == 0) {
                                Functions.relogin(TurnOutActivity.this);
                                return;
                            }

                            ArrayList<Coin> data = json.getData();
                            list.clear();
                            list.addAll(data);

                            if (json.getData().size() > 0) {
                                if (TextUtils.isEmpty(coinname)) {
                                    coinname = json.getData().get(0).getWallet_id();
                                    refreshInfo(json.getData().get(0).getWallet_name());
                                    turnOutBalanceName.setText(getResources().getString(R.string.balance_btc));
                                }else {
                                    for (Coin coin:list){
                                        if (coinname.equals( coin.getWallet_id())){
                                            coinname = coin.getWallet_id();
                                            refreshInfo(coin.getWallet_name());
                                            turnOutBalanceName.setText(getResources().getString(R.string.balance_btc));
                                            break;
                                        }
                                    }
                                }
                                startTime();

                            }

                        }
                    } catch (Exception e) {
                        IToast.show(getResources().getString(R.string.data_error));
                    }
                }
            }, false, false);
        } else {
            finish();
        }
    }

    private void refreshInfo(String coin) {

        txtvwSpinner.setText(coin);
        getSubjectInfo(coin);
        getAddressList();
    }


    private void getSubjectInfo(String name) {
        if (I_Share.isLogin()) {
            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            postParams.put("walletid", coinname);
            Functions.post(this,URLs.COININFO, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {
                }

                @Override
                public void responseSuccess(String result) {
                    turnOutTaxRate.setText("");
                    turnOutCny.setText("");
                    turnOutMoney.setText("");
                    coin = null;
                    if (Ipost.isTimeOut(result)) {
                        return;
                    }
                    try {
                        if (!TextUtils.isEmpty(result)) {
                            JsonT<Coin> json = JSON.parseObject(result, new TypeReference<JsonT<Coin>>() {
                            });
                            if (json.getIs_auth() != null && json.getIs_auth() == 0) {
                                Functions.relogin(TurnOutActivity.this);
                                return;
                            }
                            if (json.getData().getNum() != null) {
                                coin = json.getData();
                                turnOutBalance.setText(Functions.getOrdinaryCounting(json.getData().getNum() + ""));
                            }
                        }
                    } catch (Exception e) {
                        turnOutBalance.setText("");
                    }

                }
            }, true, false);
        } else {
            finish();
        }
    }

    private void getSubjectInfo1(String name) {
        if (I_Share.isLogin()) {
            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            postParams.put("walletid", coinname);
            Functions.post(this, URLs.COININFO, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {
                }

                @Override
                public void responseSuccess(String result) {
                    if (Ipost.isTimeOut(result)) {
                        return;
                    }
                    try {
                        if (!TextUtils.isEmpty(result)) {
                            JsonT<Coin> json = JSON.parseObject(result, new TypeReference<JsonT<Coin>>() {
                            });
                            if (json.getIs_auth() != null && json.getIs_auth() == 0) {
                                Functions.relogin(TurnOutActivity.this);
                                return;
                            }
                            if (json.getData().getNum() != null) {
                                turnOutBalance.setText(Functions.getOrdinaryCounting(json.getData().getNum() + ""));

                            }
                        }
                    } catch (Exception e) {
                        turnOutBalance.setText("");
                    }

                }
            }, false, false);
        } else {
            finish();
        }
    }


    /**
     * 提交转账申请
     */
    private void submitChangeOut() {
        if (I_Share.isLogin()) {
            if (TextUtils.isEmpty(turnOutMoney.getText().toString().trim())) {
                IToast.show(getResources().getString(R.string.hint_money));
                return;
            }
            if (TextUtils.isEmpty(turnOutAddress.getText().toString().trim())) {
                IToast.show(getResources().getString(R.string.account_address));
                return;
            }
            if (null !=coin.getZc_min()&&Double.parseDouble(turnOutMoney.getText().toString().trim()) < coin.getZc_min()) {
                IToast.show(getResources().getString(R.string.minMoney));
                return;
            }
            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            postParams.put("name", "WEC");
            postParams.put("amount", turnOutMoney.getText().toString());
            postParams.put("address", turnOutAddress.getText().toString());
            postParams.put("walletid", coinname);
            Functions.post(this, URLs.TRANSFERRATE, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {

                }

                @Override
                public void responseSuccess(String result) {
                    if (Ipost.isTimeOut(result)) {
                        return;
                    }
                    try {
                        if (!TextUtils.isEmpty(result)) {
                            JsonT<String> json = JSON.parseObject(result, new TypeReference<JsonT<String>>() {
                            });
                            if (json.getIs_auth() != null && json.getIs_auth() == 0) {
                                Functions.relogin(TurnOutActivity.this);
                                return;
                            }
                            if (json.getError() == 0 && json.getData() != null) {
                                IToast.show(getResources().getString(R.string.turn_out_success));
                                getSubjectInfo(coinname);
                            } else if (json.getError() == 1) {
                                IToast.show(json.getError_msg());
                            }
                        }
                    } catch (Exception e) {
                        IToast.show(getResources().getString(R.string.data_error));
                    }
                }
            }, true, false);
        } else {
            finish();
        }
    }

    /**
     * 获取地址列表
     */
    private void getAddressList() {
        if (I_Share.isLogin()) {
            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            postParams.put("coinname", "WEC");
            Functions.post(this, URLs.ADDRESSLIST, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {

                }

                @Override
                public void responseSuccess(String result) {
                    if (Ipost.isTimeOut(result)) {
                        return;
                    }
                    try {
                        addressArrayList.clear();
                        if (!TextUtils.isEmpty(result)) {
                            JsonT<ArrayList<Address>> json = JSON.parseObject(result, new TypeReference<JsonT<ArrayList<Address>>>() {
                            });
                            if (json.getIs_auth() != null && json.getIs_auth() == 0) {
                                Functions.relogin(TurnOutActivity.this);
                                return;
                            }
                            if (json.getData().size() > 0) {
                                setFraud(json.getData().get(json.getData().size() - 1));
                                addressArrayList.addAll(json.getData());
                            } else {
                                turnOutAddressSpinner.setText("");
                                turnOutAddress.setText("");
                            }
                            Address address1 = new Address();
                            address1.setAddress(getResources().getString(R.string.account_address_ad_hint));
                            addressArrayList.add(address1);
                        }
                    } catch (Exception e) {
                        IToast.show(getResources().getString(R.string.data_error));
                    }

                }
            }, true, false);
        } else {
            finish();
        }
    }

    /**
     * 获得转化率，以及人民币金额
     */
    private void getTransferRate(Double v) {
        turnOutCny.setText("≈" + ChangeUtil.m2(ChangeUtil.getCny(v, coin.getCny_price_num())) + " CNY");
        turnOutTaxRate.setText(ChangeUtil.m3(ChangeUtil.getTax(v, coin.getZc_fee_proportion(), coin.getZc_min_fee())) + " " + "WEC");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REFRESHADDRESS) {
            getAddressList();

        }
    }

    /**
     * 诈骗处理
     *
     * @param address
     */
    private void setFraud(Address address) {
        turnOutAddressSpinner.setText(address.getName());
        turnOutAddress.setText(address.getAddress());
        if (address.getType().equals("1")) {
            turnOutSubmit.setEnabled(false);
            turnOutPrompt.setText(getResources().getString(R.string.turn_out_prompt_int));
        } else {
            turnOutSubmit.setEnabled(true);
            turnOutPrompt.setText(getResources().getString(R.string.turn_out_prompt));
        }
    }

    Drawable drawable;

    /**
     */
    private void setArrowImage() {
        drawable = getResources().getDrawable(R.drawable.arrow_up);  //(API 21以上才能使用此方法)
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        turnOutAddressSpinner.setCompoundDrawables(null, null, drawable, null);
    }

    private void setArrowImageCoin() {
        drawable = getResources().getDrawable(R.drawable.arrow_up_w);  //(API 21以上才能使用此方法)
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        txtvwSpinner.setCompoundDrawables(null, null, drawable, null);
    }

    //每5秒更新一次界面（剩余时效界面显示）
    private Handler handlerTimer = new Handler() {
        public void handleMessage(Message message) {
            startTime();
            getSubjectInfo1(coinname);
        }

        ;
    };
    private static int timeRefresh = 5 * 1000;
    private Timer timer;
    private TimerTask task;

    private void startTime() {
        try {
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            if (task != null) {
                task.cancel();
                task = null;
            }
        } catch (Exception e) {

        }
        timer = new Timer();
        task = new TimerTask() {
            public void run() {
                Message message = handlerTimer.obtainMessage();
                handlerTimer.sendMessage(message);
            }
        };
        timer.schedule(task, timeRefresh);
    }

}
